<template>
  <div class="model-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">模型管理</h1>
        <p class="page-desc">管理内容模型，定义文章、栏目等数据结构和字段</p>
      </div>
      <div class="header-right">
        <el-button type="primary" icon="Plus" @click="handleAdd" class="add-btn">
          新建模型
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="站点">
          <el-select
            v-model="searchForm.siteId"
            placeholder="选择站点"
            clearable
            style="width: 150px"
          >
            <el-option label="全局模型" :value="null" />
            <el-option
              v-for="site in sites"
              :key="site.id"
              :label="site.name"
              :value="site.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="模型类型">
          <el-select
            v-model="searchForm.type"
            placeholder="选择类型"
            clearable
            style="width: 150px"
          >
            <el-option label="文章模型" value="article" />
            <el-option label="栏目模型" value="channel" />
            <el-option label="表单模型" value="form" />
            <el-option label="站点设置模型" value="site" />
            <el-option label="全局设置模型" value="global" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="模型名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入模型名称"
            style="width: 200px"
            clearable
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="handleReset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 模型列表 -->
    <div class="table-container">
      <el-table :data="modelList" v-loading="loading">
        <el-table-column prop="name" label="模型名称" min-width="150" />
        
        <el-table-column prop="type" label="模型类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="scope" label="作用范围" width="120">
          <template #default="{ row }">
            <el-tag :type="row.scope === 1 ? 'primary' : 'success'">
              {{ row.scope === 1 ? '站点' : '全局' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="site.name" label="所属站点" width="150">
          <template #default="{ row }">
            {{ row.site?.name || '全局' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="fields" label="字段数量" width="100">
          <template #default="{ row }">
            {{ row.fields?.length || 0 }}
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="orderNum" label="排序" width="80" />
        
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="handleCopy(row)">
              复制
            </el-button>
            <el-button type="text" size="small" @click="handlePreview(row)">
              预览
            </el-button>
            <el-button
              type="text"
              size="small"
              style="color: #f56c6c"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 模型表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模型名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入模型名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模型类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择模型类型">
                <el-option label="文章模型" :value="1" />
                <el-option label="栏目模型" :value="2" />
                <el-option label="站点模型" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="作用范围" prop="scope">
              <el-radio-group v-model="form.scope">
                <el-radio :label="1">站点</el-radio>
                <el-radio :label="2">全局</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属站点" prop="siteId" v-if="form.scope === 1">
              <el-select v-model="form.siteId" placeholder="请选择站点">
                <el-option
                  v-for="site in sites"
                  :key="site.id"
                  :label="site.name"
                  :value="site.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 字段配置 -->
        <el-form-item label="字段配置">
          <div class="fields-config">
            <div class="fields-header">
              <span>自定义字段</span>
              <el-button type="primary" size="small" @click="addField">
                添加字段
              </el-button>
            </div>
            
            <div class="fields-list">
              <div
                v-for="(field, index) in form.fields"
                :key="index"
                class="field-item"
              >
                <el-card>
                  <div class="field-header">
                    <span class="field-title">字段 {{ index + 1 }}</span>
                    <el-button
                      type="text"
                      size="small"
                      style="color: #f56c6c"
                      @click="removeField(index)"
                    >
                      删除
                    </el-button>
                  </div>
                  
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item label="字段名" :prop="`fields.${index}.name`">
                        <el-input
                          v-model="field.name"
                          placeholder="请输入字段名（英文）"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="字段标签" :prop="`fields.${index}.label`">
                        <el-input
                          v-model="field.label"
                          placeholder="请输入字段标签"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="字段类型" :prop="`fields.${index}.type`">
                        <el-select v-model="field.type" placeholder="选择类型">
                          <el-option label="文本框" value="text" />
                          <el-option label="多行文本" value="textarea" />
                          <el-option label="数字" value="number" />
                          <el-option label="邮箱" value="email" />
                          <el-option label="URL" value="url" />
                          <el-option label="日期" value="date" />
                          <el-option label="日期时间" value="datetime" />
                          <el-option label="单选框" value="radio" />
                          <el-option label="复选框" value="checkbox" />
                          <el-option label="下拉选择" value="select" />
                          <el-option label="开关" value="switch" />
                          <el-option label="图片" value="image" />
                          <el-option label="文件" value="file" />
                          <el-option label="富文本" value="editor" />
                          <el-option label="标签" value="tags" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item label="是否必填">
                        <el-switch
                          v-model="field.required"
                          :active-value="true"
                          :inactive-value="false"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="默认值">
                        <el-input
                          v-model="field.defaultValue"
                          placeholder="请输入默认值"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="占位符">
                        <el-input
                          v-model="field.placeholder"
                          placeholder="请输入占位符"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  
                  <!-- 选项配置 -->
                  <div v-if="['radio', 'checkbox', 'select'].includes(field.type)">
                    <el-form-item label="选项配置">
                      <div class="options-config">
                        <div
                          v-for="(option, optionIndex) in field.options"
                          :key="optionIndex"
                          class="option-item"
                        >
                          <el-input
                            v-model="option.value"
                            placeholder="选项值"
                            style="width: 120px; margin-right: 8px"
                          />
                          <el-input
                            v-model="option.label"
                            placeholder="选项标签"
                            style="width: 120px; margin-right: 8px"
                          />
                          <el-button
                            type="text"
                            size="small"
                            style="color: #f56c6c"
                            @click="removeOption(field, optionIndex)"
                          >
                            删除
                          </el-button>
                        </div>
                        <el-button
                          type="text"
                          size="small"
                          @click="addOption(field)"
                        >
                          添加选项
                        </el-button>
                      </div>
                    </el-form-item>
                  </div>
                </el-card>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="模型预览"
      width="800px"
    >
      <div class="model-preview" v-if="previewModel">
        <h3>{{ previewModel.name }}</h3>
        <p>类型: {{ getTypeText(previewModel.type) }}</p>
        <p>范围: {{ previewModel.scope === 1 ? '站点' : '全局' }}</p>
        
        <div class="fields-preview">
          <h4>字段列表</h4>
          <el-table :data="previewModel.fields" border>
            <el-table-column prop="name" label="字段名" width="120" />
            <el-table-column prop="label" label="字段标签" width="120" />
            <el-table-column prop="type" label="字段类型" width="100" />
            <el-table-column prop="required" label="必填" width="80">
              <template #default="{ row }">
                <el-tag :type="row.required ? 'danger' : 'info'" size="small">
                  {{ row.required ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="defaultValue" label="默认值" />
            <el-table-column prop="placeholder" label="占位符" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { modelApi } from '@/api/model'
import { siteApi } from '@/api/site'
import type { Model, ModelField, Site } from '@/types/api'

const loading = ref(false)
const dialogVisible = ref(false)
const previewDialogVisible = ref(false)
const submitting = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 站点数据
const sites = ref<Site[]>([])

// 搜索表单
const searchForm = reactive({
  siteId: undefined as number | undefined | null,
  name: '',
  type: undefined as number | undefined,
})

// 模型列表
const modelList = ref<Model[]>([])

// 分页信息
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0,
})

// 预览模型
const previewModel = ref<Model>()

// 表单数据
const form = ref<Partial<Model>>({
  name: '',
  type: 1,
  scope: 1,
  siteId: undefined,
  orderNum: 999999,
  status: 1,
  fields: [],
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入模型名称', trigger: 'blur' },
    { min: 1, max: 50, message: '模型名称长度在 1 到 50 个字符', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择模型类型', trigger: 'change' },
  ],
  scope: [
    { required: true, message: '请选择作用范围', trigger: 'change' },
  ],
  siteId: [
    { required: true, message: '请选择所属站点', trigger: 'change' },
  ],
}

// 对话框标题
const dialogTitle = computed(() => isEdit.value ? '编辑模型' : '新建模型')

// 获取站点列表
const getSites = async () => {
  try {
    const response = await siteApi.getSiteTree()
    sites.value = response.data
  } catch (error) {
    console.error('获取站点列表失败:', error)
  }
}

// 获取模型列表
const getModelList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm,
    }
    console.log('获取模型列表参数:', params)

    const response = await modelApi.getModelPage(params)
    console.log('模型列表响应:', response)

    if (response.code === 0) {
      modelList.value = response.data.records
      pagination.total = response.data.total
      console.log('模型列表更新成功，共', response.data.records.length, '条记录')
    } else {
      console.error('获取模型列表失败:', response.msg)
      ElMessage.error(response.msg || '获取模型列表失败')
    }
  } catch (error) {
    console.error('获取模型列表失败:', error)
    ElMessage.error('获取模型列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  getModelList()
}

// 处理重置
const handleReset = () => {
  Object.assign(searchForm, {
    siteId: undefined,
    name: '',
    type: undefined,
  })
  pagination.current = 1
  getModelList()
}

// 处理新增
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row: Model) => {
  isEdit.value = true
  form.value = { ...row }
  if (!form.value.fields) {
    form.value.fields = []
  }
  dialogVisible.value = true
}

// 处理复制
const handleCopy = (row: Model) => {
  isEdit.value = false
  form.value = {
    ...row,
    id: undefined,
    name: row.name + ' - 副本',
  }
  if (!form.value.fields) {
    form.value.fields = []
  }
  dialogVisible.value = true
}

// 处理预览
const handlePreview = (row: Model) => {
  previewModel.value = row
  previewDialogVisible.value = true
}

// 处理删除
const handleDelete = (row: Model) => {
  console.log('准备删除模型:', row)
  ElMessageBox.confirm(`确定要删除模型"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      console.log('调用删除API，模型ID:', row.id)
      const response = await modelApi.deleteModel(row.id)
      console.log('删除API响应:', response)

      if (response.code === 0) {
        ElMessage.success('删除成功')
        console.log('删除成功，重新获取模型列表')
        // 重新获取当前页数据
        await getModelList()
      } else {
        console.error('删除失败:', response.msg)
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除模型失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 处理状态变更
const handleStatusChange = async (row: Model) => {
  try {
    await modelApi.updateModelStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 添加字段
const addField = () => {
  if (!form.value.fields) {
    form.value.fields = []
  }
  form.value.fields.push({
    name: '',
    label: '',
    type: 'text',
    required: false,
    defaultValue: '',
    placeholder: '',
    options: [],
  })
}

// 删除字段
const removeField = (index: number) => {
  form.value.fields?.splice(index, 1)
}

// 添加选项
const addOption = (field: ModelField) => {
  if (!field.options) {
    field.options = []
  }
  field.options.push({
    value: '',
    label: '',
  })
}

// 删除选项
const removeOption = (field: ModelField, index: number) => {
  field.options?.splice(index, 1)
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await modelApi.updateModel(form.value.id!, form.value)
      ElMessage.success('更新成功')
    } else {
      await modelApi.createModel(form.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    getModelList()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    name: '',
    type: 1,
    scope: 1,
    siteId: undefined,
    orderNum: 999999,
    status: 1,
    fields: [],
  }
  formRef.value?.resetFields()
}

// 处理分页大小变更
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  getModelList()
}

// 处理当前页变更
const handleCurrentChange = (current: number) => {
  pagination.current = current
  getModelList()
}

// 获取类型标签类型
const getTypeTagType = (type: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',
    2: 'success',
    3: 'warning',
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '文章模型',
    2: '栏目模型',
    3: '站点模型',
  }
  return typeMap[type] || '未知'
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  getSites()
  getModelList()
})
</script>

<style scoped lang="scss">
.model-management {
  padding: 24px;
  background: #f8f9fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
    padding: 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    .header-left {
      .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #2c3e50;
        margin: 0 0 6px 0;
      }

      .page-desc {
        font-size: 14px;
        color: #6c757d;
        margin: 0;
      }
    }

    .header-right {
      .add-btn {
        height: 40px;
        padding: 0 20px;
        font-size: 14px;
        font-weight: 500;
        border-radius: 6px;
      }
    }
  }

  .search-section {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }

  .table-container {
    background: white;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }
  
  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  .fields-config {
    width: 100%;
    
    .fields-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      font-weight: 500;
    }
    
    .fields-list {
      .field-item {
        margin-bottom: 16px;
        
        .field-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          
          .field-title {
            font-weight: 500;
            color: #303133;
          }
        }
        
        .options-config {
          .option-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
          }
        }
      }
    }
  }
  
  .model-preview {
    h3 {
      margin-bottom: 16px;
      color: #303133;
    }
    
    p {
      margin-bottom: 8px;
      color: #606266;
    }
    
    .fields-preview {
      margin-top: 24px;
      
      h4 {
        margin-bottom: 12px;
        color: #303133;
      }
    }
  }
}
</style>
